/**
 * Copyright 2014 lerry
 * 
 * All right reserved.
 * 
 * Dec 16, 2014
 */
package com.bac.http;

import java.util.HashMap;
import java.util.Map;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkError;
import com.android.volley.NetworkResponse;
import com.android.volley.NoConnectionError;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.bac.bacplatform.BaseActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import android.content.Context;
import android.util.Log;

/**
 * @author lerry
 * 
 */
public class VolleyErrorHelper {

	private static boolean isNetworkProblem(Object error) {
		return (error instanceof NetworkError)
				|| (error instanceof NoConnectionError);
	}

	private static boolean isServerProblem(Object error) {
		return (error instanceof ServerError)
				|| (error instanceof AuthFailureError);
	}

	public static void handleServerError(Object err, Context context) {
		if (err instanceof TimeoutError) {
			((CommenErrorHandler) context).hanlderTimeoutError();
		} else if (isServerProblem(err)) {
			VolleyError error = (VolleyError) err;
			NetworkResponse response = error.networkResponse;
			if (response != null) {
				switch (response.statusCode) {
				case 404:
					Log.i("volley error helper-----", "404错误");
				case 422:
					try {
						// server might return error like this { "code":001,"message":"xxxx"}
						// Use "Gson" to parse the result
						HashMap<String, String> result = new Gson().fromJson(
								new String(response.data),
								new TypeToken<HashMap<String, String>>() {
								}.getType());

						if (result != null && result.containsKey("message")) {
							((CommenErrorHandler) context).hanlderErrorShowMessage(result.get("message"));
						}

					} catch (Exception e) {
						e.printStackTrace();
					}
					// invalid request
					break;
				case 401:
					// 未授权，进入登陆页面
					Log.i("volley error helper-----", "未授权，进入登陆页");
					((CommenErrorHandler) context).hanlderAutorError();
					break;
				default:((CommenErrorHandler) context).hanlderUnknowError();
				}
			}
		} else if (isNetworkProblem(err)) {
			((CommenErrorHandler) context).hanlderNetworkError();
		} else {
			((CommenErrorHandler) context).hanlderUnknowError();
		}

	}
	
	
	public interface CommenErrorHandler{
		public void hanlderTimeoutError();
		public void hanlderErrorShowMessage(String message);
		public void hanlderAutorError();
		public void hanlderUnknowError();
		public void hanlderNetworkError();
		
	}
}
